package com.ln.lnzw.activity;

import android.app.usage.UsageEvents;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.google.gson.Gson;
import com.ln.lnzw.R;
import com.ln.lnzw.adapter.ConsultationDepartmentMattersAdapter;
import com.ln.lnzw.adapter.ExpandableItemAdapter;
import com.ln.lnzw.app.AppConstant;
import com.ln.lnzw.base.BaseActivity;
import com.ln.lnzw.bean.Bean;
import com.ln.lnzw.bean.ImplementationSubjectBean;
import com.ln.lnzw.bean.Level0Item;
import com.ln.lnzw.bean.Level1Item;
import com.ln.lnzw.bean.NewImplementationSubjectBean;
import com.ln.lnzw.event.DepartmentConsultingEvent;
import com.ln.lnzw.event.SubscribeChangeEvent;
import com.ln.lnzw.fragment.TypeOfAuthorityFragment;
import com.ln.lnzw.net.HttpMethods;
import com.ln.lnzw.utils.CacheActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wuwei on 2018/4/18.
 * 我的咨询 部门所对应的事项
 */

public class ConsultationDepartmentMattersActivity extends BaseActivity {
    private static final String TAG = "第二页面";
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.rv_recyclerView)
    RecyclerView rvRecyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private String groupCDesc;//部门标识
    private String groupName;//部门名
    /**
     * 网络获取数据
     */
    private List<Bean.ResultBean.ListBeanA> sectionList = new ArrayList<>();
    /**
     * 处理之后数据
     */
    private List<MultiItemEntity> newsSectionBeanList = new ArrayList<>();
    /**
     * 数据适配器
     */
    private ConsultationDepartmentMattersAdapter myAdapter;
    private Map<String, String> imMap = new HashMap<>();
    private Map<String, String> tyMap = new HashMap<>();
    private int count = 1;
    private int lastSize;
    private int nowSize;
    private int delayMillis = 1000;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handleaffairs_service_secondary);
        ButterKnife.bind(this);
        CacheActivity.addActivity(ConsultationDepartmentMattersActivity.this);
        groupCDesc = getIntent().getStringExtra("cDesc");
        groupName = getIntent().getStringExtra("name");
        initAdapter();
        initData();

    }

    private void initData() {
        count=1;
        HttpMethods.getInstanceCenter().info.get(count+"", "10", "0", groupCDesc)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Bean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.i("666", "onSubscribe: ");

                    }

                    @Override
                    public void onNext(Bean bean) {
                        if (sectionList != null || !sectionList.isEmpty()) {
                            sectionList.clear();
                        }
                        if (newsSectionBeanList != null || !newsSectionBeanList.isEmpty()) {
                            newsSectionBeanList.clear();
                        }
                        if ("200".equals(bean.getCode())) {
                            sectionList.addAll(bean.getResult().getList());
                            makeDatas();
                            double a=bean.getResult().getTotalCount();
                            double b=bean.getResult().getPageSize();
                            if (count<Math.ceil(a/b)){
                                count=count+1;
                            }else{
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("666", "onError: " + e.toString());
                    }

                    @Override
                    public void onComplete() {
                        Log.i("666", "onComplete: ");
                    }
                });
    }

    //职权类型
    private void getTypeOfAuthority() {
        if (tyMap == null || tyMap.size() < 1) {
            tyMap.clear();
        }

        Gson gson = new Gson();
        String string = spUtils.getString(AppConstant.TYPEOFAUTHRITY);
        ImplementationSubjectBean implementationSubjectBean = gson.fromJson(string, ImplementationSubjectBean.class);
        for (int i = 0; i < implementationSubjectBean.getList_datas().size(); i++) {
            tyMap.put(implementationSubjectBean.getList_datas().get(i).getCdesc(), implementationSubjectBean.getList_datas().get(i).getCname());
        }
    }

    //实施主体
    private void getImplementation() {
        if (imMap == null || imMap.size() < 1) {
            imMap.clear();
        }
        Gson gson = new Gson();
        String string = spUtils.getString(AppConstant.IMPLEMENTATION);
        Log.i("709", "getImplementation: "+string);
        NewImplementationSubjectBean newImplementationSubjectBean = gson.fromJson(string, NewImplementationSubjectBean.class);
        for (int i = 0; i < newImplementationSubjectBean.getResult().size(); i++) {
            imMap.put(newImplementationSubjectBean.getResult().get(i).getGroupId(), newImplementationSubjectBean.getResult().get(i).getGroupName());
        }

    }

    /**
     * 根据获取到的数据来创建用到的数据集合
     */
    private void makeDatas() {
        getImplementation();
        getTypeOfAuthority();
        if (newsSectionBeanList != null || !newsSectionBeanList.isEmpty()) {
            newsSectionBeanList.clear();
        }
        if (!sectionList.isEmpty()) {
            for (int i = 0; i < sectionList.size(); i++) {
                Level0Item level0Item = new Level0Item(sectionList.get(i).getQl_name(), sectionList.get(i).getQl_name(), imMap.get(sectionList.get(i).getIdorg()), tyMap.get(sectionList.get(i).getQl_kind()));
                if (!sectionList.get(i).getList().isEmpty()) {
                    for (int j = 0; j < sectionList.get(i).getList().size(); j++) {
                        Level1Item level1Item = new Level1Item(sectionList.get(i).getList().get(j).getQl_name(), sectionList.get(i).getList().get(j).getQl_name(), sectionList.get(i).getList().get(j).getITEMGUID(),sectionList.get(i).getList().get(j).getItem_code());
                        level0Item.addSubItem(level1Item);
                    }
                }
                newsSectionBeanList.add(level0Item);
            }
        }
        myAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化adapter
     */
    private void initAdapter() {
        myAdapter = new ConsultationDepartmentMattersAdapter(newsSectionBeanList);
        rvRecyclerview.setLayoutManager(new LinearLayoutManager(this));
//        rvRecyclerview.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        rvRecyclerview.setAdapter(myAdapter);
        refreshLayout.setDisableContentWhenRefresh(true);//是否在刷新的时候禁止列表的操作
        refreshLayout.setDisableContentWhenLoading(true);//是否在加载的时候禁止列表的操作
        myAdapter.setonClickMyItem(new ConsultationDepartmentMattersAdapter.ClickMyItem() {
            @Override
            public void onClickMyItem(View v, String name, String itemCode) {
                Log.i("709", "onClickMyItem: "+name);//事项名
                Log.i("709", "onClickMyItem: "+itemCode);//事项编码
                Log.i("709", "onClickMyItem: "+groupCDesc);//部门标识
                Log.i("709", "onClickMyItem: "+groupName);//部门名称
                EventBus.getDefault().post(new DepartmentConsultingEvent(name,itemCode,groupCDesc,groupName));
                CacheActivity.finishActivity();

            }
        });
        //设置下拉刷新监听事件
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                downRefresh();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                onLoadMoreRequested();
            }
        });

    }
    /**
     * 下拉刷新
     */
    public void downRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setNoMoreData(false);
                initData();
                refreshLayout.finishRefresh();
            }
        }, delayMillis);
    }
    /**
     * 上拉加载
     */
    public void onLoadMoreRequested() {
        lastSize = sectionList.size();
        HttpMethods.getInstanceCenter().info.get(count+"", "10", "0", groupCDesc)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Bean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.i("666", "onSubscribe: ");

                    }

                    @Override
                    public void onNext(Bean bean) {
                        if ("200".equals(bean.getCode())) {
                                sectionList.addAll(bean.getResult().getList());
                            nowSize = sectionList.size();
                            if (nowSize>lastSize){
                                double a=bean.getResult().getTotalCount();
                                double b=bean.getResult().getPageSize();
                                if (count>Math.ceil(a/b)){
                                    refreshLayout.finishLoadMoreWithNoMoreData();
                                }else{
                                    makeDatas();
                                }
                                count++;
                            }else {
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("666", "onError: " + e.toString());
                    }

                    @Override
                    public void onComplete() {
                        refreshLayout.finishLoadMore();
//
                    }
                });
    }
    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        finish();
    }

}
